//@author A0100976E
package tasky.logic;

import tasky.storage.*;
import tasky.commons.Task;
import tasky.history.*;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.joda.time.DateTime;
import org.joda.time.DateTimeComparator;
import org.joda.time.Interval;

public class AddCommand implements Command {
	public ArrayList<Task> tasks;
	public AddParser addParser;
	public Storage storage;
	public History history;
	public Logger logger;
	String data;
	String errorMessage;
	String warningMessage;
	String output;
	private boolean isError = false;
	private boolean warning = false;
	private static final String ADD_SUCCESSFUL = "\" %s \"  is added successfully.\n";
	private static final String COMMAND_ADD = "add";
	private static final String EMPTY_TASK_CONTENT = "";
	private static final String ERRORMSG_EMPTY_TASK_CONTENT = "Empty task content entered.\n";
	private static final String WARNING_MSG_DEADLINE_EXPIRED = "deadline is before current date!\n";
	private static final String WARNING_MSG_END_DATE_EXPIRED = "End date is before current date!\n";
	private static final String WARNINGMSG_OVERLAPTASK_HEADER = "%s collides with:\n";
	private static final String WARNINGMSG_OVERLAPTASK = "%d. %s\n";
	private static final int BASE_INDEX = 1;
	
	public AddCommand(ArrayList<Task> tasks, Storage storage, History history,
			Logger logger) {
		this.tasks = tasks;
		this.addParser = new AddParser();
		this.storage = storage;
		this.history = history;
		this.logger = logger;
		errorMessage = "";
	}

	@Override
	public void acceptInput(String data) {
		this.data = data;
	}

	@Override
	public void execute() {
		Task newTask = null;

		try {
			newTask = addParser.parse(data, tasks);
		} catch (ParseException e) {
			errorMessage = e.getMessage();
			logger.log(Level.INFO, errorMessage);
			isError = true;
		}

		if (newTask == null) {
			isError = true;
		} else if (newTask.getContent().equals(EMPTY_TASK_CONTENT)) {
			errorMessage = ERRORMSG_EMPTY_TASK_CONTENT;
			isError = true;
		} else {
			history.storeUndo(tasks, COMMAND_ADD);
			tasks.add(newTask);
			output = String.format(ADD_SUCCESSFUL, newTask.getUserInput());
		}

		if (!isError) {
			checkExpiredDate(newTask);
			checkInterval(newTask);
		}
	}

	@Override
	public String outputToUser() {
		if (isError) {
			output = errorMessage;
		}
		return output;
	}

	@Override
	public String save() throws IOException {
		return storage.writeToStorage(tasks);
	}

	@Override
	public boolean isError() {
		return isError;
	}

	public void checkExpiredDate(Task newTask) {
		DateTime todayDate = new DateTime();
		DateTimeComparator compareDate = DateTimeComparator
				.getDateOnlyInstance();
		if (newTask.getDeadline() != null
				&& (compareDate.compare(newTask.getDeadline(), todayDate) < 0)) {

			warningMessage = WARNING_MSG_DEADLINE_EXPIRED;
			warning = true;

		} else if (newTask.getEnd() != null) {
			if (newTask.getEnd() != null
					&& (compareDate.compare(newTask.getEnd(), todayDate) < 0)) {
				warningMessage = WARNING_MSG_END_DATE_EXPIRED;
				warning = true;
			}
		}
	}

	private void checkInterval(Task newTask) {
		boolean overlapExists = false;
		Interval newTaskInterval, taskInterval;
		StringBuilder overlappingTask = new StringBuilder();
		overlappingTask.append(String.format(WARNINGMSG_OVERLAPTASK_HEADER,
				newTask.getContent()));

		if (containsInterval(newTask)) {
			newTaskInterval = obtainInterval(newTask);
			for (Task task : tasks) {
				if(containsInterval(task)) {
					taskInterval = obtainInterval(task);
					if (task != newTask && newTaskInterval.overlaps(taskInterval)) {
						overlappingTask.append(String.format(
								WARNINGMSG_OVERLAPTASK, tasks.indexOf(task)+BASE_INDEX,
								task.getContent()));
						overlapExists = true;
					}
				}
			}
			if (overlapExists) {
				warningMessage = overlappingTask.toString();
				warning = true;
			}
		}
	}

	private boolean containsInterval(Task newTask) {

		DateTime startDate = newTask.getStart();
		DateTime endDate = newTask.getEnd();

		if (startDate != null && endDate != null) {
			return true;
		} else {
			return false;
		}

	}

	private Interval obtainInterval(Task newTask) {
		Interval taskInterval = new Interval(newTask.getStart(),
				newTask.getEnd());
		return taskInterval;
	}

	public boolean getWarning() {
		return warning;
	}

	public String getWarningMessage() {
		return warningMessage;
	}
}